//
//  ZYSLoginViewController.m
//  shopSN
//
//  Created by imac on 2016/10/24.
//  Copyright © 2016年 yisu. All rights reserved.
//

#import "ZYSLoginViewController.h"
#import "ZForgetPasswordViewController.h"
#import "ZCenterMemberCertificateViewController.h"
#import "ZYSRegisterViewController.h"

@interface ZYSLoginViewController ()<UITextFieldDelegate>

/** 手机号 */
@property (nonatomic, strong) UITextField *phoneTF;

/** 密码 */
@property (nonatomic, strong) UITextField *passwordTF;
//是否有短信验证
@property (nonatomic) BOOL isSms;

@end

@implementation ZYSLoginViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];


    [self initView];
}
//初始化界面
- (void)initView{
    UIImageView *backV = [[UIImageView  alloc]initWithFrame:CGRectMake(0, 0, __kWidth, __kHeight)];
    [self.view addSubview:backV];
    [self.view sendSubviewToBack:backV];

    backV.image = MImage(@"ysbg");

    UIImageView *logoIV = [[UIImageView alloc]initWithFrame:CGRectMake((__kWidth-144)/2, ((__kHeight-200)/2-46)/2, 144, 46)];
    [self.view addSubview:logoIV];
    logoIV.backgroundColor = [UIColor clearColor];
    logoIV.image = MImage(@"yslogo");

    UIView *mainV = [[UIView alloc]initWithFrame:CGRectMake(0, (__kHeight-200)/2, __kWidth, 400)];
    [self.view addSubview:mainV];
    mainV.backgroundColor = [UIColor clearColor];

    for (int i=0; i<2; i++) {
        UIView *inputV= [[UIView alloc]initWithFrame:CGRectMake(25, 42*i, __kWidth-50, 36)];
        [mainV addSubview:inputV];
        inputV.backgroundColor = [UIColor whiteColor];
        inputV.alpha=0.6;
        inputV.layer.borderWidth = 1;
        inputV.layer.borderColor = HEXCOLOR(0xdedede).CGColor;

        //1 图片视图
        UIView *iheadView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 36, 36)];
        [inputV addSubview:iheadView];
        iheadView.backgroundColor = [UIColor whiteColor];

        //中间竖线
        UIImageView *lineIV = [[UIImageView alloc] initWithFrame:CGRectMake(35, 0, 1, 36)];
        [iheadView addSubview:lineIV];
        lineIV.backgroundColor = HEXCOLOR(0xdedede);

        //图片
        UIImageView *iheadIV = [[UIImageView alloc]initWithFrame:CGRectMake(9, 9, 18, 18)];
        [inputV addSubview:iheadIV];
        iheadIV.contentMode = UIViewContentModeScaleAspectFit;
        //2 输入框
        UITextField *inputTF = [[UITextField alloc]initWithFrame:CGRectMake(CGRectXW(iheadView)+5, 8, CGRectW(inputV)-36-10, 20)];
        inputTF.backgroundColor = [UIColor clearColor];
        [inputV addSubview:inputTF];
        inputTF.font = MFont(15);
        //        inputTF.tag = i+33;

        inputTF.delegate =self;
        if (i) {
            inputTF.placeholder  = @"请输入6-16位密码";
            _passwordTF=inputTF;
            _passwordTF.tag = 33;
            _passwordTF.secureTextEntry = YES;
            //iheadIV.frame = CGRectMake(9, 9, 18, 18);
            iheadIV.image = [UIImage imageNamed:@"mima"];
        }else{
            inputTF.placeholder = @"请输入手机号码";
            _phoneTF=inputTF;
            //iheadIV.frame = CGRectMake(10, 9, 16, 18);
            iheadIV.image = [UIImage imageNamed:@"ysuser"];
        }

    }

    //自动登录按钮
    UIButton *atLoginBtn = [[UIButton alloc]initWithFrame:CGRectMake(25, 100, 80, 20)];
    [mainV addSubview:atLoginBtn];
    atLoginBtn.titleLabel.font = MFont(14);
    [atLoginBtn setTitle:@"自动登录" forState:BtnNormal];
    [atLoginBtn setTitleColor:[UIColor lightGrayColor] forState:BtnNormal];
    [atLoginBtn setImage:MImage(@"kuangwu") forState:BtnNormal];
    [atLoginBtn setImage:MImage(@"gouxuan_f") forState:BtnStateSelected];
    atLoginBtn.backgroundColor =[UIColor clearColor];
    atLoginBtn.titleEdgeInsets = UIEdgeInsetsMake(2.5,-atLoginBtn.titleLabel.bounds.size.width-16, 2.5, 0);
    atLoginBtn.imageEdgeInsets = UIEdgeInsetsMake(3,0, 2, 64);
    [atLoginBtn addTarget:self action:@selector(chooseAuto:) forControlEvents:BtnTouchUpInside];

   //忘记密码按钮
    UIButton *forgetBtn = [[UIButton alloc]initWithFrame:CGRectMake(__kWidth-105, 100, 80, 20)];
    [mainV addSubview:forgetBtn];
    forgetBtn.titleLabel.font = MFont(14);
    [forgetBtn setTitle:@"忘记密码？" forState:BtnNormal];
    [forgetBtn setTitleColor:[UIColor lightGrayColor] forState:BtnNormal];
    forgetBtn.backgroundColor = [UIColor clearColor];
    [forgetBtn addTarget:self action:@selector(forgetPassword) forControlEvents:BtnTouchUpInside];


    //7 登录按钮
    UIButton *loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(25, CGRectYH(forgetBtn)+35, __kWidth-50, 40)];
    [mainV addSubview:loginBtn];
    loginBtn.backgroundColor = __DefaultColor;
    loginBtn.layer.cornerRadius = 4.0f;
    loginBtn.titleLabel.font = MFont(15);
    [loginBtn setTitle:@"立即登录" forState:BtnNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:BtnNormal];
    [loginBtn addTarget:self action:@selector(loginBtnAction) forControlEvents:BtnTouchUpInside];


    //注册
    UIButton *logonBtn = [[UIButton alloc]initWithFrame:CGRectMake((__kWidth-75)/2, __kHeight-75, 75, 30)];
    [self.view addSubview:logonBtn];
    logonBtn.backgroundColor = [UIColor clearColor];
    logonBtn.titleLabel.font = MFont(15);
    [logonBtn setTitle:@"用户注册" forState:BtnNormal];
    [logonBtn setTitleColor:__DefaultColor forState:BtnNormal];
    logonBtn.layer.cornerRadius = 4.0f;
    logonBtn.layer.borderColor = __DefaultColor.CGColor;
    logonBtn.layer.borderWidth = 1;

    [logonBtn addTarget:self action:@selector(logon) forControlEvents:BtnTouchUpInside];

}


#pragma mark ==自动登录设置按钮==
- (void)chooseAuto:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected) {
        [UdStorage storageObject:@"1" forKey:Auto];
    }else{
        [UdStorage storageObject:@"0" forKey:Auto];
    }
}

#pragma mark ==忘记密码==
-(void)forgetPassword{
    NSLog(@"忘记密码");
    ZForgetPasswordViewController *vc = [[ZForgetPasswordViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ==立即登录==
- (void)loginBtnAction{
    NSLog(@"登录");
    [self checkTextFieldContent];
    NSString *path = @"Login/login";
    NSDictionary *params =@{@"username":_phoneTF.text,
                            @"password":_passwordTF.text,
                            };
    [ZHttpRequestService POST:path withParameters:params success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {

            NSArray *data=jsonDic[@"data"];
            NSDictionary *dic=data[0];
            NSString *userid=[Utils getTextStrByText:dic[@"token"]];
            [UdStorage storageObject:userid forKey:Userid];

            NSString *userType=[Utils getTextStrByText:dic[@"grade_name"]];
            [UdStorage storageObject:userType forKey:UserType];


            NSString *userPhone=_phoneTF.text;
            [UdStorage storageObject:userPhone forKey:UserPhone];

            [[NSNotificationCenter defaultCenter] postNotificationName:CDidLoginNotification object:nil];
            if ([userType isEqualToString:@"游客"]) {
                //[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0]animated:NO];
                //进入会员资格页面
                ZCenterMemberCertificateViewController *vc = [[ZCenterMemberCertificateViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [SXLoadingView showAlertHUD:@"登录成功" duration:SXLoadingTime];
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0]animated:YES];
            }





        }else{
            NSString *message = jsonDic[@"message"];
            //[SXLoadingView showAlertHUD:@"注册失败" duration:SXLoadingTime];
            [SXLoadingView showAlertHUD:message duration:2];
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"登录失败" duration:SXLoadingTime];
        //NSLog(@"%@",error);
    } animated:YES withView:nil];

}
#pragma mark ==注册==
- (void)logon{
    NSLog(@"注册");
    [self getSMS];
}

//短信验证开通
-(void)getSMS{
    [ZHttpRequestService POST:@"Login/isOpenSms" withParameters:nil success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            NSArray *data=jsonDic[@"data"];
            if (data.count) {
                NSDictionary *dic=data[0];
                NSString *str = dic[@"sms_open"];
                if ([str isEqualToString:@"0"]) {
                    _isSms = YES;
                }else{
                    _isSms = NO;
                }
                ZYSRegisterViewController *vc = [[ZYSRegisterViewController alloc]init];
                vc.isSms = _isSms;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    } failure:^(NSError *error) {
        
    } animated:YES withView:nil];
}



//判断输入内容是否正确
- (void)checkTextFieldContent {
    if (IsNilString(_phoneTF.text)) {
        [SXLoadingView showAlertHUD:@"手机号码不能为空" duration:SXLoadingTime];
        return;
    }

    if (_phoneTF.text.length!=11) {
        [SXLoadingView showAlertHUD:@"手机号码错误" duration:SXLoadingTime];
        return;
    }

    if (IsNilString(_passwordTF.text)) {
        [SXLoadingView showAlertHUD:@"密码不能为空" duration:SXLoadingTime];
        return;
    }
}


#pragma mark - ===== 移除键盘 =====
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (_phoneTF || _passwordTF) {
        [self.view endEditing:YES];
    }
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
